#pragma once

#include<iostream>
#include<string>
#include<fstream>
#include<unordered_map>
#include "Comm.hpp"
#include "Log.hpp"

const std::string gdictname = "dict.txt";
const std::string gpath = "./";
const std::string gsep = ": "; // 分隔符

using namespace LogModule;

class Dictionary
{
    bool LoadDictionary()
    {
        std::string file = _path + _filename;
        std::fstream in (file.c_str(), std::ios::in);
        // int fd = ::open(file.c_str(), O_CREAT|O_RDONLY, 0666);
        // if(fd < 0)
        // {
        //     LOG(LogLevel::ERROR)<<"open fail";
        //     return false;
        // }
        if(!in.is_open())
        {
            LOG(LogLevel::ERROR)<<"open fail";
            return false;
        }

        std::string line;
        while(std::getline(in,line))
        {
            std::string key;
            std::string value;
            if(SplitString(line, &key, &value, gsep))
            {
                _dictionary.insert(std::make_pair(key, value));
            }
        }
        in.close();

        return true;
    }
public:
    Dictionary(const std::string& path = gpath, const std::string& filename = gdictname)
    :_path(path)
    ,_filename(filename)
    {
        LoadDictionary();
    }

    std::string Translate(const std::string& word)
    {
        auto iter = _dictionary.find(word);
        if(iter == _dictionary.end())   return "None";
        return iter->second;
    }
private:
    std::unordered_map<std::string, std::string> _dictionary;
    std::string _path;
    std::string _filename;
};